﻿using System.Linq.Expressions;

namespace zijian666.Data;
internal static class ExpressionExtensions
{
    public static MemberInfo[] ParseMemberInit<T>(this Expression<Func<T>> expression, out T entity)
    {
        ArgumentNullException.ThrowIfNull(expression);
        if (expression.Body is not MemberInitExpression memberInitExpression)
        {
            throw new ArgumentException("表达式必须是 MemberInitExpression 类型", nameof(expression));
        }


        var bindings = memberInitExpression.Bindings;

        // 创建实体对象
        entity = expression.Compile()();
        var members = new MemberInfo[bindings.Count];
        for (var i = 0; i < bindings.Count; i++)
        {
            var memberAssignment = (MemberAssignment)bindings[i];
            members[i] = memberAssignment.Member;
        }
        return members;
    }

}
